﻿// MIT License
//
// Copyright (c) 2021-present zuohuaijun, Daming Co.,Ltd and Contributors
//
// 电话/微信：18020030720 QQ群1：87333204 QQ群2：252381476

using Admin.NET.Application.Const;
using Admin.Net.InformationPlatform.Entity;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using Nest;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.OpenXmlFormats.Spreadsheet;
using Admin.Net.InformationPlatform.Service.Product.Dto;
using Admin.Net.InformationPlatform.Entity.Product;
using Admin.Net.InformationPlatform.Service.Product.Dto.View;
using Furion.FriendlyException;
using Admin.Net.InformationPlatform.Entity.Order;
using Microsoft.Extensions.Primitives;
using SjEntityClass;
using Admin.NET.Core;
using Admin.Net.InformationPlatform.Service.Order.Dto;
using Admin.Net.InformationPlatform.Service.Product.Dto.T100;
using CustomerInput = Admin.Net.InformationPlatform.Service.Product.Dto.CustomerInput;

namespace Admin.Net.InformationPlatform.Service.Product;
/// <summary>
/// 客户下单
/// </summary>
[ApiDescriptionSettings(groups: "PlaceOrder", Name = "在线下单", Tag = "客户信息处理", Order = 200)]
public class OrderCustomerService : IDynamicApiController, ITransient
{

    /// <summary>
    /// 单例数据链接
    /// </summary>
    ISqlSugarClient db;
    /// <summary>
    /// T100数据库
    /// </summary>
    private SqlSugarProvider _T100Db;
    private SqlSugarProvider _SjDb;
    private SqlSugarProvider _plm;
    private SqlSugarProvider _Dilon;
    private SqlSugarProvider _T100TestView;


    /// <summary>
    /// 用户信息
    /// </summary>
    TokenUser _User;
    /// <summary>
    /// 报备客户管理模块
    /// </summary>
    /// <param name="db"></param>
    public OrderCustomerService(ISqlSugarClient db)
    {
        this.db = db;
        this._T100Db = this.db.AsTenant().GetConnection(T100Const.ConfigId);
        this._SjDb = this.db.AsTenant().GetConnection(SJDB.ConfigId);
        this._plm = this.db.AsTenant().GetConnection(PLM.ConfigId);
        this._Dilon = this.db.AsTenant().GetConnection(Dilon.ConfigId);
        this._T100TestView = this.db.AsTenant().GetConnection(T100TestView.ConfigId);
        // 获取 `Jwt` 存储的信息 企业编号与据点信息
        _User = Util.SjCommonUtil.GetT100UserTokenInfo(_T100Db, _Dilon);

    }

    /// <summary>
    /// 生成不重复订单号
    /// </summary>
    /// <returns></returns>
    private string GetOrderNo() {

        TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);

        string orderNo = DateTime.Now.Date.ToString("yyyyMMdd") + Convert.ToInt64(ts.TotalSeconds).ToString();

        return orderNo;
    }


    /// <summary>
    /// 客户编号模糊查询
    /// </summary>
    /// <param name="user"></param>
    /// <returns></returns>
    [HttpPost("/Order/GetUserMessage")]
    public async Task<List<UserMessage>> SelectUserNameMessage([FromBody] UserMessageInput user)
    {
        //权限验证
        #region
        /*  var LoginRoles = _Dilon.Queryable<SysUserRole>()
                  .LeftJoin<SysUser>((r, u) => (r.UserId == u.Id))
                        .Where((r, u) => r.UserId.ToString() == _User.ID)
                       .Select((r, u) => new SalesmanRole
                       {
                           USERID = u.Account,
                           USERNAME = u.RealName,
                           ROLEID = r.RoleId.ToString()
                       }).ToList();
          int role = LoginRoles.Where(u => u.ROLEID == "14631543922501").Count();//判断是否拥有营销中心角色
          int role1 = LoginRoles.Where(u => u.ROLEID == "14620909947205").Count();//判断是否拥有销售助理角色


          List<T100UserMessage> t100List = _T100TestView.Ado.SqlQuery<T100UserMessage>($@"WITH RecursiveCTE AS(
                  SELECT lastname,
                      ID, managerid
                  FROM HrmResource
                  WHERE ID = (SELECT id from HrmResource where loginid = '007637')-- 将 @YourID 替换为您要查询的根 ID
                  UNION ALL
                  SELECT yt.lastname,yt.ID, yt.managerid
                  FROM HrmResource yt
                  JOIN RecursiveCTE cte ON yt.managerid = cte.ID
              )
              SELECT lastname,
              ID, managerid
              FROM RecursiveCTE;").ToList();





          List<string> a = new List<string>();

          //销售总监 能看到全部数据
          if (role > 0)
          {
              //查询城市经理下的业务员信息
              var values = _Dilon.Queryable<SysUserRole>()
                  .LeftJoin<SysUser>((r, u) => (r.UserId == u.Id))
                  .Where((r, u) => r.RoleId.ToString() == "14620909947205")
                  .Where((r, u) => u.OrgId.ToString() == _User.OrgId)
                   .Select((r, u) => new SalesmanRoles
                   {
                       BBR = u.Account,
                   }).ToList();

              for (int i = 0; i < values.Count; i++)
              {
                  a.Add(values[i].BBR);
              }
          }

          //销售助理角色
          if (role1 > 0)
          {



              //查询城市经理下的业务员信息
              var values = _Dilon.Queryable<SysUserRole>()
                  .LeftJoin<SysUser>((r, u) => (r.UserId == u.Id))
                  .Where((r, u) => r.RoleId.ToString() == "14620909947205")
                  .Where((r, u) => u.OrgId.ToString() == _User.OrgId)
                   .Select((r, u) => new SalesmanRoles
                   {
                       BBR = u.Account,
                   }).ToList();

              for (int i = 0; i < values.Count; i++)
              {
                  a.Add(values[i].BBR);
              }
          }


          //中间职位只能看到自己和对应下级的数据
          if (role == 0 && role1==0  )
          {
              //查询城市经理下的业务员信息
              var values = _Dilon.Queryable<SysUserRole>()
                  .LeftJoin<SysUser>((r, u) => (r.UserId == u.Id))
                  .Where((r, u) => r.RoleId.ToString() == "14478138094149")
                  .Where((r, u) => u.OrgId.ToString() == _User.OrgId)
                   .Select((r, u) => new SalesmanRoles
                   {
                       BBR = u.Account,
                   }).ToList();

              for (int i = 0; i < values.Count; i++)
              {
                  a.Add(values[i].BBR);
              }
          }*/

        #endregion
        var viewList = await _T100TestView.Queryable<DHAXMT200_VIEW_PMABENT>()
             .Where(it => it.DHPMAB007.Contains(user.UserName))
           //  .WhereIF(role == 1, (l) => l.DHPMAB006 == _User.UserId)//业务员只能看自己的数据
           //  .WhereIF(role1 == 1, (l) => a.Contains(l.DHPMAB006))//城市经理可以看到自己名下业务员数据
             .Select(a => new UserMessage
             {
                 UserNo = a.DHPMAB006,
                 UserName = a.DHPMAB007

             }).ToListAsync();

        return viewList;

    }

    /// <summary>
    /// /根据客户简称查询
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost("/Order/GetCustomerMessage")]
    public UserMessageOut GetCustomerMessage([FromBody] CustomerInput input) {

        //缺了一个部门下属的验证

        List<Cxmm200View> viewList = _T100TestView.Ado.SqlQuery<Cxmm200View>($@"select * from cxmm200_view where cxmm200_view002='{input.CustName}'").ToList();

        if (viewList.Count==0) {
            return null;
        }

        List<DHAXMM200_CUSTOMS008> DHAXMM200_CUSTOMS008 = _T100TestView.Ado.SqlQuery<DHAXMM200_CUSTOMS008>($@"select * from DHAXMM200_customs008 where pmaa001='{viewList[0].CXMM200_VIEW001}'").ToList();

        List<DHAXMT200_VIEW_PMAD002> DHAXMT200_VIEW_PMAD002 = _T100TestView.Ado.SqlQuery<DHAXMT200_VIEW_PMAD002>($@"select * from DHAXMT200_VIEW_PMAD002 where DHPMAD001='{viewList[0].CXMM200_VIEW001}'").ToList();
        if (DHAXMT200_VIEW_PMAD002.Count == 0)
        {
            throw Oops.Oh("请填写收款条件！");
        }

        List<DHAXMM202_CUSTOMS005> DHAXMM202_CUSTOMS005 = _T100TestView.Ado.SqlQuery<DHAXMM202_CUSTOMS005>($@"select * from DHAXMM202_customs005 where PMAB001='{viewList[0].CXMM200_VIEW001}'").ToList();

        if (DHAXMM202_CUSTOMS005.Count == 0)
        {
            throw Oops.Oh("请填写客户惯用交易币种！");
        }

     /*   List<string> DHPMAD005List = new List<string>();
        List<string> DHPMAD006List = new List<string>();
        foreach (var item in DHAXMT200_VIEW_PMAD002)
        {
            DHPMAD005List.Add(item.DHPMAD005);
            DHPMAD006List.Add(item.DHPMAD006);
        }*/
        

      //  if (viewList.Count==1) {
            UserMessageOut userMessage = new UserMessageOut();

            userMessage.UserNo = viewList[0].CXMM200_VIEW001;//用户编号
            userMessage.UserName = viewList[0].CXMM200_VIEW002;//用户名称
            userMessage.CustNumber = this.GetOrderNo(); //订单编号
            userMessage.OrderDate = DateTime.Now.Date.ToString("yyyy-MM-dd");//订单日期
            userMessage.CustNo = viewList[0].CXMM200_VIEW021;//默认业务员编号
            userMessage.CustName = viewList[0].CXMM200_VIEW022;//默认业务员名称
            userMessage.UserDepartment = viewList[0].CXMM200_VIEW023;//业务部门编号
            userMessage.UserDepartmentName= viewList[0].CXMM200_VIEW024;//业务部门名称
            userMessage.OrderData = 1; //订单性质编号
            userMessage.OrderDataName = "一般订单";//订单性质 待定
            userMessage.OrderType = "XM61";//订单类型编号 待定
            userMessage.OrderTypeName = "其他客户订单";//订单类型 待定
            userMessage.CheckStatus = DHAXMM200_CUSTOMS008[0].PMACSTUS.Equals("Y") ? "已审核" : "未审核";//审核状态
           // userMessage.TaxType = DHPMAD005List;//收款条件
          //  userMessage.TaxTypeName = DHPMAD006List;//收款条件名称
             userMessage.TaxType = DHAXMT200_VIEW_PMAD002[0].DHPMAD005;//收款条件
             userMessage.TaxTypeName = DHAXMT200_VIEW_PMAD002[0].DHPMAD006;//收款条件名称
            userMessage.CoinType = DHAXMM202_CUSTOMS005.Count > 0 ? DHAXMM202_CUSTOMS005[0].pmab083 : "";//币种
            userMessage.CoinTypeName = DHAXMM202_CUSTOMS005.Count > 0 ? DHAXMM202_CUSTOMS005[0].ooail003 : "";//币种信息
            userMessage.GetPriceType = viewList[0].CXMM200_VIEW042; //取价方式
            userMessage.GetPriceTypeName= viewList[0].CXMM200_VIEW043;//取价方式名称

            return userMessage;
       // }

       


    }



}
